const now = new Date();
const sevenDaysLater = new Date(now);
sevenDaysLater.setDate(now.getDate() + 6);
const app = getApp();
const weixinId = app.globalData.weixinId;
Page({
  data: {
    timeRange: [
      // 小时范围
      Array.from({ length: 24 }, (_, i) => i.toString().padStart(2, '0')),
      // 分钟范围，仅允许00和30
      ['00', '30'],
    ],
    timeValue: [new Date().getHours().toString().padStart(2, '0'), '00'], // 默认值
    date: '请选择日期',
    show: false,
    showDate: false,
    minDate: new Date(now).getTime(),
    maxDate: new Date(sevenDaysLater).getTime(),
    selectedIndex: -1,
    meetings: [],
    array: ['暂存', '待审核', '审核通过', '审核不通过', '预约成功', '撤回'],
    index: 0, // 默认选中的索引
    selectedText: '请选择状态', // 默认显示的文本
    beginDate: null,
    endDate: null,
    showDialog: false,
    canAuth: false,
    modifiedItem: {
      Theme: '',
      BeginTime: '',
      EndTime: '',
      RoomName: '',
      DateTime: '',
    },
    option: [
      { text: '请选择会议室', value: 0, RoomID: 0 },
      { text: '一楼小型会议室【B3-106】', value: 1, RoomID: 1 },
      { text: '一楼中型会议室【B3-109】', value: 2, RoomID: 2 },
      { text: '学术报告厅【B3-117】', value: 3, RoomID: 3 },
      { text: '五楼中型会议室【B3-506】', value: 4, RoomID: 4 },
      { text: '五楼小会议室【B3-516】', value: 5, RoomID: 5 },
      { text: '六楼中型会议室【B3-605】', value: 6, RoomID: 6 },
    ],
    value: 0,
  },
  onPullDownRefresh: function () {
    const timeoutId = setTimeout(() => {
      wx.stopPullDownRefresh();
    }, 2000);
  },

  onLoad(options) {
    this.fetchMeetings();
  },

  bindBeginTimeChange(e) {
    const { value } = e.detail;
    // 获取选中的小时和分钟
    const selectedHour = this.data.timeRange[0][value[0]];
    const selectedMinute = this.data.timeRange[1][value[1]];

    // 构造新的时间字符串
    const newBeginTime = `${selectedHour}:${selectedMinute}`;

    // 使用 setData 更新数据，确保视图更新
    this.setData({
      'modifiedItem.BeginTime': newBeginTime,
    });
  },

  bindEndTimeChange(e) {
    const { value } = e.detail;
    // 获取选中的小时和分钟
    const selectedHour = this.data.timeRange[0][value[0]];
    const selectedMinute = this.data.timeRange[1][value[1]];

    // 构造新的时间字符串
    const newEndTime = `${selectedHour}:${selectedMinute}`;

    // 使用 setData 更新数据，确保视图更新
    this.setData({
      'modifiedItem.EndTime': newEndTime,
    });
  },

  del() {
    const that = this;
    wx.showModal({
      content: '确认取消该预约',
      complete: (res) => {
        if (res.cancel) {
        }
        if (res.confirm) {
          const params = {
            WeiXinID: weixinId,
            ReservationID: that.data.modifiedItem.ReservationID,
          };
          //删除预约
          wx.request({
            url:
              'https://itlab.ctgu.edu.cn/labapi/MeetingManage/DeleteReservation',
            method: 'POST',
            data: params,
            header: {
              Cookie: app.globalData.cookie,
            },
            success(res) {
              wx.showToast({
                title: res.data.status === 0 ? res.data.msg : '删除失败',
                duration: 2000,
                icon: 'none',
                success: function () {},
                complete: function () {
                  setTimeout(() => {
                    wx.reLaunch({
                      url: '/pages/mymeeting/mymeeting',
                    });
                  }, 2000);
                },
              });
            },
          });
        }
      },
    });
  },

  onConfirmDate(e) {
    this.setData({
      showDate: false,
      'modifiedItem.DateTime': this.formatDate(e.detail),
    });
  },
  onDisplayDate() {
    this.setData({ showDate: true });
  },
  onCloseDate() {
    this.setData({ showDate: false });
  },

  onDateChange(e) {
    const value = e.detail;
    const modifiedItem = { ...this.data.modifiedItem, DateTime: value };
    this.setData({ modifiedItem });
  },

  openDoor(e) {
    const queryParam = {
      WeiXinID: weixinId,
      ReservationID: e.target.dataset.info.ReservationID,
    };
    wx.showLoading({
      title: '正在解除门禁',
    });
    //解除门禁
    wx.request({
      url: 'https://itlab.ctgu.edu.cn/labapi/MeetingManage/OpenDoor',
      method: 'POST',
      data: queryParam,
      header: {
        Cookie: app.globalData.cookie,
      },
      success(res) {
        if (res.data.status == 0) {
          wx.reLaunch({
            url: '/pages/mymeeting/mymeeting',
          });
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'error',
          });
        }
      },
    });
    wx.hideLoading();
  },
  confirmAuth(e) {
    const canAuth = e.currentTarget.dataset.info.canAuth; // 获取 data-can-auth 的值
    const that = this;
    if (e.currentTarget.dataset.info.AuthStatus) {
      wx.showModal({
        content: '已解除门禁',
      });
      return;
    }
    if (canAuth) {
      wx.showModal({
        content: '确定解除门禁',
        success(res) {
          if (res.confirm) {
            //发送远程开门申请
            that.openDoor(e);
          } else if (res.cancel) {
          }
        },
      });
    } else {
      wx.showModal({
        content: '不在授权门禁时间范围内',
        success(res) {
          if (res.confirm) {
          } else if (res.cancel) {
          }
        },
      });
    }
  },
  //比较时间差
  contrastTime(time) {
    const begintime = new Date(time);
    // 计算时间差（以毫秒为单位）
    const timeDifference = Math.abs(now - begintime);
    // 将时间差转换为分钟
    const minutesDifference = timeDifference / (1000 * 60);
    // 检查时间差是否小于等于30分钟
    const isWithin30Minutes = minutesDifference <= 30;
    return isWithin30Minutes;
  },
  // 下拉菜单变化
  onPickerChange: function (e) {
    const index = e.detail.value;
    const selectedOption = this.data.option[index];
    if (selectedOption) {
      const modifiedItem = {
        ...this.data.modifiedItem,
        RoomName: selectedOption.text,
      };
      this.setData({ value: index, modifiedItem });
    }
  },

  // 点击修改按钮
  onModify: function (e) {
    const item = e.currentTarget.dataset.info;
    const DateTime = this.formatDate(item.BeginTime);
    const BeginTime = this.convertToHHMM(item.BeginTime);
    const EndTime = this.convertToHHMM(item.EndTime);
    this.setData({
      showDialog: true,
      modifiedItem: { ...item, DateTime, BeginTime, EndTime }, // 复制一份当前项的数据
    });
  },

  // 确认修改
  onConfirmModify: function (e) {
    const modifiedItem = this.data.modifiedItem;
    const params = {
      WeiXinID: weixinId,
      ReservationID: modifiedItem.ReservationID,
      Theme: modifiedItem.Theme,
      BeginTime: modifiedItem.DateTime + ' ' + modifiedItem.BeginTime,
      EndTime: modifiedItem.DateTime + ' ' + modifiedItem.EndTime,
      RoomID: modifiedItem.RoomID,
    };
    console.log(params);

    wx.request({
      url: 'https://itlab.ctgu.edu.cn/labapi/MeetingManage/SaveReservation',
      method: 'POST',
      header: {
        Cookie: app.globalData.cookie,
      },
      data: params,
      header: {
        'content-type': 'application/json',
      },
      success(res) {
        console.log(res);
        if (res.data.status === 0)
          wx.showToast({
            title: '修改成功',
            icon: 'success',
            duration: 1500,
            mask: false,
          });
        else {
          wx.showToast({
            title: '修改失败',
            icon: 'error',
            duration: 1500,
            mask: false,
          });
        }
      },
      fail(err) {
        console.error(err.errMsg);
      },
    });

    // 关闭对话框
    this.setData({ showDialog: false });
  },

  // 取消修改
  onCancelModify: function (e) {
    // 关闭对话框
    this.setData({ showDialog: false });
  },

  // 开始时间变化
  onBeginTimeChange: function (e) {
    const value = e.detail;
    const modifiedItem = { ...this.data.modifiedItem, BeginTime: value };
    this.setData({ modifiedItem });
  },

  // 结束时间变化
  onEndTimeChange: function (e) {
    const value = e.detail;
    const modifiedItem = { ...this.data.modifiedItem, EndTime: value };
    this.setData({ modifiedItem });
  },

  // 获取会议信息
  fetchMeetings: function () {
    const that = this;
    const params = {
      WeiXinID: weixinId,
      BeginDate: that.data.BeginDate ? that.data.BeginDate : '',
      EndDate: that.data.EndDate ? that.data.EndDate : '',
      Status: that.data.index ? that.data.index : 4,
    };
    console.log('获取预约信息的参数', params);
    const url = `https://itlab.ctgu.edu.cn/labapi/MeetingManage/GetMeetingReservation`;
    wx.showLoading({
      title: '加载中',
    });

    // 获取会议信息
    wx.request({
      url: url,
      method: 'GET',
      data: params,
      success: function (res) {
        if (res.data.status === 0) {
          const meetings = res.data.DataInfo.DataList.map((meeting) => ({
            ...meeting,
            canAuth: that.contrastTime(meeting.BeginTime),
            formattedTime: that.formatDateTime(
              meeting.BeginTime,
              meeting.EndTime
            ),
            statusText: that.getStatusText(meeting.Status),
          }));
          that.setData({ meetings });
        }
      },
    });
    wx.hideLoading();
  },

  // 格式化日期
  formatDateTime: function (beginTime, endTime) {
    // 将日期字符串转换为 iOS 支持的格式
    const convertToSupportedFormat = (dateTimeStr) => {
      // 检查并转换日期时间格式
      if (dateTimeStr.includes('T')) {
        return dateTimeStr; // 已经是 ISO 格式
      } else if (dateTimeStr.includes(' ')) {
        // 处理 "yyyy-MM-dd HH:mm:ss" 格式
        return dateTimeStr.replace(/ /g, 'T');
      } else {
        // 处理 "yyyy-MM-dd" 格式
        return dateTimeStr + 'T00:00:00';
      }
    };

    const beginDate = new Date(convertToSupportedFormat(beginTime));
    const endDate = new Date(convertToSupportedFormat(endTime));

    const month = (beginDate.getMonth() + 1).toString().padStart(2, '0');
    const day = beginDate.getDate().toString().padStart(2, '0');
    const weekday = ['日', '一', '二', '三', '四', '五', '六'][
      beginDate.getDay()
    ];
    const beginHour = beginDate.getHours().toString().padStart(2, '0');
    const beginMinute = beginDate.getMinutes().toString().padStart(2, '0');
    const endHour = endDate.getHours().toString().padStart(2, '0');
    const endMinute = endDate.getMinutes().toString().padStart(2, '0');

    return `${month}-${day}星期${weekday} ${beginHour}:${beginMinute}-${endHour}:${endMinute}`;
  },

  // 将2024-10-11T21:30:00变成21:30
  convertToHHMM(isoTimeString) {
    // 使用正则表达式来匹配ISO 8601格式的时间部分
    const regex = /(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})/;
    const match = isoTimeString.match(regex);

    if (!match) {
      throw new Error(
        'Invalid ISO 8601 time format. Expected format: YYYY-MM-DDTHH:MM:SS'
      );
    }

    // 提取小时和分钟部分
    const hours = match[4];
    const minutes = match[5];

    // 返回格式化后的时间字符串
    return `${hours}:${minutes}`;
  },

  // 预约信息
  getStatusText: function (status) {
    switch (status) {
      case 1:
        return '待审核';
      case 2:
        return '已取消';
      case 3:
        return '已拒绝';
      case 4:
        return '预约成功';
      default:
        return '未知状态';
    }
  },

  bindPickerChange: function (e) {
    const selectedIndex = e.detail.value;
    const selectedValue = this.data.array[selectedIndex];
    this.setData({
      index: selectedIndex,
      selectedText: selectedValue,
    });
    this.fetchMeetings();
  },

  onDisplay() {
    this.setData({ show: true });
  },
  onClose() {
    this.setData({ show: false });
  },

  // 通用的日期格式化函数
  formatDate(date) {
    const d = new Date(date);
    const year = d.getFullYear();
    const month = (d.getMonth() + 1).toString().padStart(2, '0');
    const day = d.getDate().toString().padStart(2, '0');
    return `${year}-${month}-${day}`;
  },

  onConfirm(event) {
    const [start, end] = event.detail;
    this.setData({
      show: false,
      // date: `${this.formatDate(start)} 至 ${this.formatDate(end)}`,
      BeginDate: this.formatDate(start),
      EndDate: this.formatDate(end),
    });
    this.fetchMeetings();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    wx.setNavigationBarTitle({
      title: '我的预约',
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});
